typo
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 *
5 * @package MediaWiki
6 */
7
8 /** */
9 require_once( 'normal/UtfNormal.php' );
10
11 $wgTitleInterwikiCache = array();
12 $wgTitleCache = array();
13
14 define ( 'GAID_FOR_UPDATE', 1 );
15
16 # Title::newFromTitle maintains a cache to avoid
17 # expensive re-normalization of commonly used titles.
18 # On a batch operation this can become a memory leak
19 # if not bounded. After hitting this many titles,
20 # reset the cache.
21 define( 'MW_TITLECACHE_MAX', 1000 );
22
23 /**
24 * Title class
25 * - Represents a title, which may contain an interwiki designation or namespace
26 * - Can fetch various kinds of data from the database, albeit inefficiently.
27 *
28 * @package MediaWiki
29 */
30 class Title {
31 /**
32 * All member variables should be considered private
33 * Please use the accessor functions
34 */
35
36 /**#@+
37 * @access private
38 */
39
40 var $mTextform; # Text form (spaces not underscores) of the main part
41 var $mUrlform; # URL-encoded form of the main part
42 var $mDbkeyform; # Main part with underscores
43 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
44 var $mInterwiki; # Interwiki prefix (or null string)
45 var $mFragment; # Title fragment (i.e. the bit after the #)
46 var $mArticleID; # Article ID, fetched from the link cache on demand
47 var $mLatestID; # ID of most recent revision
48 var $mRestrictions; # Array of groups allowed to edit this article
49 # Only null or "sysop" are supported
50 var $mRestrictionsLoaded; # Boolean for initialisation on demand
51 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
52 var $mDefaultNamespace; # Namespace index when there is no namespace
53 # Zero except in {{transclusion}} tags
54 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
55 /**#@-*/
56
57
58 /**
59 * Constructor
60 * @access private
61 */
62 /* private */ function Title() {
63 $this->mInterwiki = $this->mUrlform =
64 $this->mTextform = $this->mDbkeyform = '';
65 $this->mArticleID = -1;
66 $this->mNamespace = NS_MAIN;
67 $this->mRestrictionsLoaded = false;
68 $this->mRestrictions = array();
69 # Dont change the following, NS_MAIN is hardcoded in several place
70 # See bug #696
71 $this->mDefaultNamespace = NS_MAIN;
72 $this->mWatched = NULL;
73 $this->mLatestID = false;
74 }
75
76 /**
77 * Create a new Title from a prefixed DB key
78 * @param string $key The database key, which has underscores
79 * instead of spaces, possibly including namespace and
80 * interwiki prefixes
81 * @return Title the new object, or NULL on an error
82 * @static
83 * @access public
84 */
85 /* static */ function newFromDBkey( $key ) {
86 $t = new Title();
87 $t->mDbkeyform = $key;
88 if( $t->secureAndSplit() )
89 return $t;
90 else
91 return NULL;
92 }
93
94 /**
95 * Create a new Title from text, such as what one would
96 * find in a link. Decodes any HTML entities in the text.
97 *
98 * @param string $text the link text; spaces, prefixes,
99 * and an initial ':' indicating the main namespace
100 * are accepted
101 * @param int $defaultNamespace the namespace to use if
102 * none is specified by a prefix
103 * @return Title the new object, or NULL on an error
104 * @static
105 * @access public
106 */
107 function newFromText( $text, $defaultNamespace = NS_MAIN ) {
108 global $wgTitleCache;
109 $fname = 'Title::newFromText';
110 wfProfileIn( $fname );
111
112 if( is_object( $text ) ) {
113 wfDebugDieBacktrace( 'Title::newFromText given an object' );
114 }
115
116 /**
117 * Wiki pages often contain multiple links to the same page.
118 * Title normalization and parsing can become expensive on
119 * pages with many links, so we can save a little time by
120 * caching them.
121 *
122 * In theory these are value objects and won't get changed...
123 */
124 if( $defaultNamespace == NS_MAIN && isset( $wgTitleCache[$text] ) ) {
125 wfProfileOut( $fname );
126 return $wgTitleCache[$text];
127 }
128
129 /**
130 * Convert things like &eacute; &#257; or &#x3017; into real text...
131 */
132 $filteredText = Sanitizer::decodeCharReferences( $text );
133
134 $t =& new Title();
135 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
136 $t->mDefaultNamespace = $defaultNamespace;
137
138 static $cachedcount = 0 ;
139 if( $t->secureAndSplit() ) {
140 if( $defaultNamespace == NS_MAIN ) {
141 if( $cachedcount >= MW_TITLECACHE_MAX ) {
142 # Avoid memory leaks on mass operations...
143 $wgTitleCache = array();
144 $cachedcount=0;
145 }
146 $cachedcount++;
147 $wgTitleCache[$text] =& $t;
148 }
149 wfProfileOut( $fname );
150 return $t;
151 } else {
152 wfProfileOut( $fname );
153 $ret = NULL;
154 return $ret;
155 }
156 }
157
158 /**
159 * Create a new Title from URL-encoded text. Ensures that
160 * the given title's length does not exceed the maximum.
161 * @param string $url the title, as might be taken from a URL
162 * @return Title the new object, or NULL on an error
163 * @static
164 * @access public
165 */
166 function newFromURL( $url ) {
167 global $wgLegalTitleChars;
168 $t = new Title();
169
170 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
171 # but some URLs used it as a space replacement and they still come
172 # from some external search tools.
173 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
174 $url = str_replace( '+', ' ', $url );
175 }
176
177 $t->mDbkeyform = str_replace( ' ', '_', $url );
178 if( $t->secureAndSplit() ) {
179 return $t;
180 } else {
181 return NULL;
182 }
183 }
184
185 /**
186 * Create a new Title from an article ID
187 *
188 * @todo This is inefficiently implemented, the page row is requested
189 * but not used for anything else
190 *
191 * @param int $id the page_id corresponding to the Title to create
192 * @return Title the new object, or NULL on an error
193 * @access public
194 * @static
195 */
196 function newFromID( $id ) {
197 $fname = 'Title::newFromID';
198 $dbr =& wfGetDB( DB_SLAVE );
199 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
200 array( 'page_id' => $id ), $fname );
201 if ( $row !== false ) {
202 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
203 } else {
204 $title = NULL;
205 }
206 return $title;
207 }
208
209 /**
210 * Create a new Title from a namespace index and a DB key.
211 * It's assumed that $ns and $title are *valid*, for instance when
212 * they came directly from the database or a special page name.
213 * For convenience, spaces are converted to underscores so that
214 * eg user_text fields can be used directly.
215 *
216 * @param int $ns the namespace of the article
217 * @param string $title the unprefixed database key form
218 * @return Title the new object
219 * @static
220 * @access public
221 */
222 function &makeTitle( $ns, $title ) {
223 $t =& new Title();
224 $t->mInterwiki = '';
225 $t->mFragment = '';
226 $t->mNamespace = intval( $ns );
227 $t->mDbkeyform = str_replace( ' ', '_', $title );
228 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
229 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
230 $t->mTextform = str_replace( '_', ' ', $title );
231 return $t;
232 }
233
234 /**
235 * Create a new Title frrom a namespace index and a DB key.
236 * The parameters will be checked for validity, which is a bit slower
237 * than makeTitle() but safer for user-provided data.
238 *
239 * @param int $ns the namespace of the article
240 * @param string $title the database key form
241 * @return Title the new object, or NULL on an error
242 * @static
243 * @access public
244 */
245 function makeTitleSafe( $ns, $title ) {
246 $t = new Title();
247 $t->mDbkeyform = Title::makeName( $ns, $title );
248 if( $t->secureAndSplit() ) {
249 return $t;
250 } else {
251 return NULL;
252 }
253 }
254
255 /**
256 * Create a new Title for the Main Page
257 *
258 * @static
259 * @return Title the new object
260 * @access public
261 */
262 function newMainPage() {
263 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
264 }
265
266 /**
267 * Create a new Title for a redirect
268 * @param string $text the redirect title text
269 * @return Title the new object, or NULL if the text is not a
270 * valid redirect
271 * @static
272 * @access public
273 */
274 function newFromRedirect( $text ) {
275 global $wgMwRedir;
276 $rt = NULL;
277 if ( $wgMwRedir->matchStart( $text ) ) {
278 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
279 # categories are escaped using : for example one can enter:
280 # #REDIRECT [[:Category:Music]]. Need to remove it.
281 if ( substr($m[1],0,1) == ':') {
282 # We don't want to keep the ':'
283 $m[1] = substr( $m[1], 1 );
284 }
285
286 $rt = Title::newFromText( $m[1] );
287 # Disallow redirects to Special:Userlogout
288 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL && preg_match( '/^Userlogout/i', $rt->getText() ) ) {
289 $rt = NULL;
290 }
291 }
292 }
293 return $rt;
294 }
295
296 #----------------------------------------------------------------------------
297 # Static functions
298 #----------------------------------------------------------------------------
299
300 /**
301 * Get the prefixed DB key associated with an ID
302 * @param int $id the page_id of the article
303 * @return Title an object representing the article, or NULL
304 * if no such article was found
305 * @static
306 * @access public
307 */
308 function nameOf( $id ) {
309 $fname = 'Title::nameOf';
310 $dbr =& wfGetDB( DB_SLAVE );
311
312 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
313 if ( $s === false ) { return NULL; }
314
315 $n = Title::makeName( $s->page_namespace, $s->page_title );
316 return $n;
317 }
318
319 /**
320 * Get a regex character class describing the legal characters in a link
321 * @return string the list of characters, not delimited
322 * @static
323 * @access public
324 */
325 function legalChars() {
326 global $wgLegalTitleChars;
327 return $wgLegalTitleChars;
328 }
329
330 /**
331 * Get a string representation of a title suitable for
332 * including in a search index
333 *
334 * @param int $ns a namespace index
335 * @param string $title text-form main part
336 * @return string a stripped-down title string ready for the
337 * search index
338 */
339 /* static */ function indexTitle( $ns, $title ) {
340 global $wgContLang;
341 require_once( 'SearchEngine.php' );
342
343 $lc = SearchEngine::legalSearchChars() . '&#;';
344 $t = $wgContLang->stripForSearch( $title );
345 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
346 $t = strtolower( $t );
347
348 # Handle 's, s'
349 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
350 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
351
352 $t = preg_replace( "/\\s+/", ' ', $t );
353
354 if ( $ns == NS_IMAGE ) {
355 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
356 }
357 return trim( $t );
358 }
359
360 /*
361 * Make a prefixed DB key from a DB key and a namespace index
362 * @param int $ns numerical representation of the namespace
363 * @param string $title the DB key form the title
364 * @return string the prefixed form of the title
365 */
366 /* static */ function makeName( $ns, $title ) {
367 global $wgContLang;
368
369 $n = $wgContLang->getNsText( $ns );
370 return $n == '' ? $title : "$n:$title";
371 }
372
373 /**
374 * Returns the URL associated with an interwiki prefix
375 * @param string $key the interwiki prefix (e.g. "MeatBall")
376 * @return the associated URL, containing "$1", which should be
377 * replaced by an article title
378 * @static (arguably)
379 * @access public
380 */
381 function getInterwikiLink( $key ) {
382 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
383 global $wgInterwikiCache;
384 $fname = 'Title::getInterwikiLink';
385
386 wfProfileIn( $fname );
387
388 $key = strtolower( $key );
389
390 $k = $wgDBname.':interwiki:'.$key;
391 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
392 wfProfileOut( $fname );
393 return $wgTitleInterwikiCache[$k]->iw_url;
394 }
395
396 if ($wgInterwikiCache) {
397 wfProfileOut( $fname );
398 return Title::getInterwikiCached( $key );
399 }
400
401 $s = $wgMemc->get( $k );
402 # Ignore old keys with no iw_local
403 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
404 $wgTitleInterwikiCache[$k] = $s;
405 wfProfileOut( $fname );
406 return $s->iw_url;
407 }
408
409 $dbr =& wfGetDB( DB_SLAVE );
410 $res = $dbr->select( 'interwiki',
411 array( 'iw_url', 'iw_local', 'iw_trans' ),
412 array( 'iw_prefix' => $key ), $fname );
413 if( !$res ) {
414 wfProfileOut( $fname );
415 return '';
416 }
417
418 $s = $dbr->fetchObject( $res );
419 if( !$s ) {
420 # Cache non-existence: create a blank object and save it to memcached
421 $s = (object)false;
422 $s->iw_url = '';
423 $s->iw_local = 0;
424 $s->iw_trans = 0;
425 }
426 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
427 $wgTitleInterwikiCache[$k] = $s;
428
429 wfProfileOut( $fname );
430 return $s->iw_url;
431 }
432
433 /**
434 * Fetch interwiki prefix data from local cache in constant database
435 *
436 * More logic is explained in DefaultSettings
437 *
438 * @return string URL of interwiki site
439 * @access public
440 */
441 function getInterwikiCached( $key ) {
442 global $wgDBname, $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
443 global $wgTitleInterwikiCache;
444 static $db, $site;
445
446 if (!$db)
447 $db=dba_open($wgInterwikiCache,'r','cdb');
448 /* Resolve site name */
449 if ($wgInterwikiScopes>=3 and !$site) {
450 $site = dba_fetch("__sites:{$wgDBname}", $db);
451 if ($site=="")
452 $site = $wgInterwikiFallbackSite;
453 }
454 $value = dba_fetch("{$wgDBname}:{$key}", $db);
455 if ($value=='' and $wgInterwikiScopes>=3) {
456 /* try site-level */
457 $value = dba_fetch("_{$site}:{$key}", $db);
458 }
459 if ($value=='' and $wgInterwikiScopes>=2) {
460 /* try globals */
461 $value = dba_fetch("__global:{$key}", $db);
462 }
463 if ($value=='undef')
464 $value='';
465 $s = (object)false;
466 $s->iw_url = '';
467 $s->iw_local = 0;
468 $s->iw_trans = 0;
469 if ($value!='') {
470 list($local,$url)=explode(' ',$value,2);
471 $s->iw_url=$url;
472 $s->iw_local=(int)$local;
473 }
474 $wgTitleInterwikiCache[$wgDBname.':interwiki:'.$key] = $s;
475 return $s->iw_url;
476 }
477 /**
478 * Determine whether the object refers to a page within
479 * this project.
480 *
481 * @return bool TRUE if this is an in-project interwiki link
482 * or a wikilink, FALSE otherwise
483 * @access public
484 */
485 function isLocal() {
486 global $wgTitleInterwikiCache, $wgDBname;
487
488 if ( $this->mInterwiki != '' ) {
489 # Make sure key is loaded into cache
490 $this->getInterwikiLink( $this->mInterwiki );
491 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
492 return (bool)($wgTitleInterwikiCache[$k]->iw_local);
493 } else {
494 return true;
495 }
496 }
497
498 /**
499 * Determine whether the object refers to a page within
500 * this project and is transcludable.
501 *
502 * @return bool TRUE if this is transcludable
503 * @access public
504 */
505 function isTrans() {
506 global $wgTitleInterwikiCache, $wgDBname;
507
508 if ($this->mInterwiki == '' || !$this->isLocal())
509 return false;
510 # Make sure key is loaded into cache
511 $this->getInterwikiLink( $this->mInterwiki );
512 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
513 return (bool)($wgTitleInterwikiCache[$k]->iw_trans);
514 }
515
516 /**
517 * Update the page_touched field for an array of title objects
518 * @todo Inefficient unless the IDs are already loaded into the
519 * link cache
520 * @param array $titles an array of Title objects to be touched
521 * @param string $timestamp the timestamp to use instead of the
522 * default current time
523 * @static
524 * @access public
525 */
526 function touchArray( $titles, $timestamp = '' ) {
527
528 if ( count( $titles ) == 0 ) {
529 return;
530 }
531 $dbw =& wfGetDB( DB_MASTER );
532 if ( $timestamp == '' ) {
533 $timestamp = $dbw->timestamp();
534 }
535 /*
536 $page = $dbw->tableName( 'page' );
537 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
538 $first = true;
539
540 foreach ( $titles as $title ) {
541 if ( $wgUseFileCache ) {
542 $cm = new CacheManager($title);
543 @unlink($cm->fileCacheName());
544 }
545
546 if ( ! $first ) {
547 $sql .= ',';
548 }
549 $first = false;
550 $sql .= $title->getArticleID();
551 }
552 $sql .= ')';
553 if ( ! $first ) {
554 $dbw->query( $sql, 'Title::touchArray' );
555 }
556 */
557 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
558 // do them in small chunks:
559 $fname = 'Title::touchArray';
560 foreach( $titles as $title ) {
561 $dbw->update( 'page',
562 array( 'page_touched' => $timestamp ),
563 array(
564 'page_namespace' => $title->getNamespace(),
565 'page_title' => $title->getDBkey() ),
566 $fname );
567 }
568 }
569
570 #----------------------------------------------------------------------------
571 # Other stuff
572 #----------------------------------------------------------------------------
573
574 /** Simple accessors */
575 /**
576 * Get the text form (spaces not underscores) of the main part
577 * @return string
578 * @access public
579 */
580 function getText() { return $this->mTextform; }
581 /**
582 * Get the URL-encoded form of the main part
583 * @return string
584 * @access public
585 */
586 function getPartialURL() { return $this->mUrlform; }
587 /**
588 * Get the main part with underscores
589 * @return string
590 * @access public
591 */
592 function getDBkey() { return $this->mDbkeyform; }
593 /**
594 * Get the namespace index, i.e. one of the NS_xxxx constants
595 * @return int
596 * @access public
597 */
598 function getNamespace() { return $this->mNamespace; }
599 /**
600 * Get the namespace text
601 * @return string
602 * @access public
603 */
604 function getNsText() {
605 global $wgContLang;
606 return $wgContLang->getNsText( $this->mNamespace );
607 }
608 /**
609 * Get the namespace text of the subject (rather than talk) page
610 * @return string
611 * @access public
612 */
613 function getSubjectNsText() {
614 global $wgContLang;
615 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) );
616 }
617
618 /**
619 * Get the interwiki prefix (or null string)
620 * @return string
621 * @access public
622 */
623 function getInterwiki() { return $this->mInterwiki; }
624 /**
625 * Get the Title fragment (i.e. the bit after the #)
626 * @return string
627 * @access public
628 */
629 function getFragment() { return $this->mFragment; }
630 /**
631 * Get the default namespace index, for when there is no namespace
632 * @return int
633 * @access public
634 */
635 function getDefaultNamespace() { return $this->mDefaultNamespace; }
636
637 /**
638 * Get title for search index
639 * @return string a stripped-down title string ready for the
640 * search index
641 */
642 function getIndexTitle() {
643 return Title::indexTitle( $this->mNamespace, $this->mTextform );
644 }
645
646 /**
647 * Get the prefixed database key form
648 * @return string the prefixed title, with underscores and
649 * any interwiki and namespace prefixes
650 * @access public
651 */
652 function getPrefixedDBkey() {
653 $s = $this->prefix( $this->mDbkeyform );
654 $s = str_replace( ' ', '_', $s );
655 return $s;
656 }
657
658 /**
659 * Get the prefixed title with spaces.
660 * This is the form usually used for display
661 * @return string the prefixed title, with spaces
662 * @access public
663 */
664 function getPrefixedText() {
665 global $wgContLang;
666 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
667 $s = $this->prefix( $this->mTextform );
668 $s = str_replace( '_', ' ', $s );
669 $this->mPrefixedText = $s;
670 }
671 return $this->mPrefixedText;
672 }
673
674 /**
675 * Get the prefixed title with spaces, plus any fragment
676 * (part beginning with '#')
677 * @return string the prefixed title, with spaces and
678 * the fragment, including '#'
679 * @access public
680 */
681 function getFullText() {
682 global $wgContLang;
683 $text = $this->getPrefixedText();
684 if( '' != $this->mFragment ) {
685 $text .= '#' . $this->mFragment;
686 }
687 return $text;
688 }
689
690 /**
691 * Get a URL-encoded title (not an actual URL) including interwiki
692 * @return string the URL-encoded form
693 * @access public
694 */
695 function getPrefixedURL() {
696 $s = $this->prefix( $this->mDbkeyform );
697 $s = str_replace( ' ', '_', $s );
698
699 $s = wfUrlencode ( $s ) ;
700
701 # Cleaning up URL to make it look nice -- is this safe?
702 $s = str_replace( '%28', '(', $s );
703 $s = str_replace( '%29', ')', $s );
704
705 return $s;
706 }
707
708 /**
709 * Get a real URL referring to this title, with interwiki link and
710 * fragment
711 *
712 * @param string $query an optional query string, not used
713 * for interwiki links
714 * @return string the URL
715 * @access public
716 */
717 function getFullURL( $query = '' ) {
718 global $wgContLang, $wgServer, $wgRequest;
719
720 if ( '' == $this->mInterwiki ) {
721 $url = $this->getLocalUrl( $query );
722
723 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
724 // Correct fix would be to move the prepending elsewhere.
725 if ($wgRequest->getVal('action') != 'render') {
726 $url = $wgServer . $url;
727 }
728 } else {
729 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
730
731 $namespace = $wgContLang->getNsText( $this->mNamespace );
732 if ( '' != $namespace ) {
733 # Can this actually happen? Interwikis shouldn't be parsed.
734 $namespace .= ':';
735 }
736 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
737 if( $query != '' ) {
738 if( false === strpos( $url, '?' ) ) {
739 $url .= '?';
740 } else {
741 $url .= '&';
742 }
743 $url .= $query;
744 }
745 if ( '' != $this->mFragment ) {
746 $url .= '#' . $this->mFragment;
747 }
748 }
749 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
750 return $url;
751 }
752
753 /**
754 * Get a URL with no fragment or server name. If this page is generated
755 * with action=render, $wgServer is prepended.
756 * @param string $query an optional query string; if not specified,
757 * $wgArticlePath will be used.
758 * @return string the URL
759 * @access public
760 */
761 function getLocalURL( $query = '' ) {
762 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
763
764 if ( $this->isExternal() ) {
765 $url = $this->getFullURL();
766 } else {
767 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
768 if ( $query == '' ) {
769 $url = str_replace( '$1', $dbkey, $wgArticlePath );
770 } else {
771 global $wgActionPaths;
772 $url = false;
773 if( !empty( $wgActionPaths ) &&
774 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
775 {
776 $action = urldecode( $matches[2] );
777 if( isset( $wgActionPaths[$action] ) ) {
778 $query = $matches[1];
779 if( isset( $matches[4] ) ) $query .= $matches[4];
780 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
781 if( $query != '' ) $url .= '?' . $query;
782 }
783 }
784 if ( $url === false ) {
785 if ( $query == '-' ) {
786 $query = '';
787 }
788 $url = "{$wgScript}?title={$dbkey}&{$query}";
789 }
790 }
791
792 // FIXME: this causes breakage in various places when we
793 // actually expected a local URL and end up with dupe prefixes.
794 if ($wgRequest->getVal('action') == 'render') {
795 $url = $wgServer . $url;
796 }
797 }
798 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
799 return $url;
800 }
801
802 /**
803 * Get an HTML-escaped version of the URL form, suitable for
804 * using in a link, without a server name or fragment
805 * @param string $query an optional query string
806 * @return string the URL
807 * @access public
808 */
809 function escapeLocalURL( $query = '' ) {
810 return htmlspecialchars( $this->getLocalURL( $query ) );
811 }
812
813 /**
814 * Get an HTML-escaped version of the URL form, suitable for
815 * using in a link, including the server name and fragment
816 *
817 * @return string the URL
818 * @param string $query an optional query string
819 * @access public
820 */
821 function escapeFullURL( $query = '' ) {
822 return htmlspecialchars( $this->getFullURL( $query ) );
823 }
824
825 /**
826 * Get the URL form for an internal link.
827 * - Used in various Squid-related code, in case we have a different
828 * internal hostname for the server from the exposed one.
829 *
830 * @param string $query an optional query string
831 * @return string the URL
832 * @access public
833 */
834 function getInternalURL( $query = '' ) {
835 global $wgInternalServer;
836 $url = $wgInternalServer . $this->getLocalURL( $query );
837 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
838 return $url;
839 }
840
841 /**
842 * Get the edit URL for this Title
843 * @return string the URL, or a null string if this is an
844 * interwiki link
845 * @access public
846 */
847 function getEditURL() {
848 global $wgServer, $wgScript;
849
850 if ( '' != $this->mInterwiki ) { return ''; }
851 $s = $this->getLocalURL( 'action=edit' );
852
853 return $s;
854 }
855
856 /**
857 * Get the HTML-escaped displayable text form.
858 * Used for the title field in <a> tags.
859 * @return string the text, including any prefixes
860 * @access public
861 */
862 function getEscapedText() {
863 return htmlspecialchars( $this->getPrefixedText() );
864 }
865
866 /**
867 * Is this Title interwiki?
868 * @return boolean
869 * @access public
870 */
871 function isExternal() { return ( '' != $this->mInterwiki ); }
872
873 /**
874 * Does the title correspond to a protected article?
875 * @param string $what the action the page is protected from,
876 * by default checks move and edit
877 * @return boolean
878 * @access public
879 */
880 function isProtected( $action = '' ) {
881 global $wgRestrictionLevels;
882 if ( -1 == $this->mNamespace ) { return true; }
883
884 if( $action == 'edit' || $action == '' ) {
885 $r = $this->getRestrictions( 'edit' );
886 foreach( $wgRestrictionLevels as $level ) {
887 if( in_array( $level, $r ) && $level != '' ) {
888 return( true );
889 }
890 }
891 }
892
893 if( $action == 'move' || $action == '' ) {
894 $r = $this->getRestrictions( 'move' );
895 foreach( $wgRestrictionLevels as $level ) {
896 if( in_array( $level, $r ) && $level != '' ) {
897 return( true );
898 }
899 }
900 }
901
902 return false;
903 }
904
905 /**
906 * Is $wgUser is watching this page?
907 * @return boolean
908 * @access public
909 */
910 function userIsWatching() {
911 global $wgUser;
912
913 if ( is_null( $this->mWatched ) ) {
914 if ( -1 == $this->mNamespace || 0 == $wgUser->getID()) {
915 $this->mWatched = false;
916 } else {
917 $this->mWatched = $wgUser->isWatched( $this );
918 }
919 }
920 return $this->mWatched;
921 }
922
923 /**
924 * Can $wgUser perform $action this page?
925 * @param string $action action that permission needs to be checked for
926 * @return boolean
927 * @access private
928 */
929 function userCan($action) {
930 $fname = 'Title::userCan';
931 wfProfileIn( $fname );
932
933 global $wgUser;
934 if( NS_SPECIAL == $this->mNamespace ) {
935 wfProfileOut( $fname );
936 return false;
937 }
938 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
939 // from taking effect -ævar
940 if( NS_MEDIAWIKI == $this->mNamespace &&
941 !$wgUser->isAllowed('editinterface') ) {
942 wfProfileOut( $fname );
943 return false;
944 }
945
946 if( $this->mDbkeyform == '_' ) {
947 # FIXME: Is this necessary? Shouldn't be allowed anyway...
948 wfProfileOut( $fname );
949 return false;
950 }
951
952 # protect global styles and js
953 if ( NS_MEDIAWIKI == $this->mNamespace
954 && preg_match("/\\.(css|js)$/", $this->mTextform )
955 && !$wgUser->isAllowed('editinterface') ) {
956 wfProfileOut( $fname );
957 return false;
958 }
959
960 # protect css/js subpages of user pages
961 # XXX: this might be better using restrictions
962 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
963 if( NS_USER == $this->mNamespace
964 && preg_match("/\\.(css|js)$/", $this->mTextform )
965 && !$wgUser->isAllowed('editinterface')
966 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
967 wfProfileOut( $fname );
968 return false;
969 }
970
971 foreach( $this->getRestrictions($action) as $right ) {
972 // Backwards compatibility, rewrite sysop -> protect
973 if ( $right == 'sysop' ) {
974 $right = 'protect';
975 }
976 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
977 wfProfileOut( $fname );
978 return false;
979 }
980 }
981
982 if( $action == 'move' &&
983 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
984 wfProfileOut( $fname );
985 return false;
986 }
987
988 if( $action == 'create' ) {
989 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
990 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
991 return false;
992 }
993 }
994
995 wfProfileOut( $fname );
996 return true;
997 }
998
999 /**
1000 * Can $wgUser edit this page?
1001 * @return boolean
1002 * @access public
1003 */
1004 function userCanEdit() {
1005 return $this->userCan('edit');
1006 }
1007
1008 /**
1009 * Can $wgUser move this page?
1010 * @return boolean
1011 * @access public
1012 */
1013 function userCanMove() {
1014 return $this->userCan('move');
1015 }
1016
1017 /**
1018 * Would anybody with sufficient privileges be able to move this page?
1019 * Some pages just aren't movable.
1020 *
1021 * @return boolean
1022 * @access public
1023 */
1024 function isMovable() {
1025 return Namespace::isMovable( $this->getNamespace() )
1026 && $this->getInterwiki() == '';
1027 }
1028
1029 /**
1030 * Can $wgUser read this page?
1031 * @return boolean
1032 * @access public
1033 */
1034 function userCanRead() {
1035 global $wgUser;
1036
1037 if( $wgUser->isAllowed('read') ) {
1038 return true;
1039 } else {
1040 global $wgWhitelistRead;
1041
1042 /** If anon users can create an account,
1043 they need to reach the login page first! */
1044 if( $wgUser->isAllowed( 'createaccount' )
1045 && $this->getNamespace() == NS_SPECIAL
1046 && $this->getText() == 'Userlogin' ) {
1047 return true;
1048 }
1049
1050 /** some pages are explicitly allowed */
1051 $name = $this->getPrefixedText();
1052 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1053 return true;
1054 }
1055
1056 # Compatibility with old settings
1057 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
1058 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1059 return true;
1060 }
1061 }
1062 }
1063 return false;
1064 }
1065
1066 /**
1067 * Is this a talk page of some sort?
1068 * @return bool
1069 * @access public
1070 */
1071 function isTalkPage() {
1072 return Namespace::isTalk( $this->getNamespace() );
1073 }
1074
1075 /**
1076 * Is this a .css or .js subpage of a user page?
1077 * @return bool
1078 * @access public
1079 */
1080 function isCssJsSubpage() {
1081 return ( NS_USER == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
1082 }
1083 /**
1084 * Is this a .css subpage of a user page?
1085 * @return bool
1086 * @access public
1087 */
1088 function isCssSubpage() {
1089 return ( NS_USER == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
1090 }
1091 /**
1092 * Is this a .js subpage of a user page?
1093 * @return bool
1094 * @access public
1095 */
1096 function isJsSubpage() {
1097 return ( NS_USER == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
1098 }
1099 /**
1100 * Protect css/js subpages of user pages: can $wgUser edit
1101 * this page?
1102 *
1103 * @return boolean
1104 * @todo XXX: this might be better using restrictions
1105 * @access public
1106 */
1107 function userCanEditCssJsSubpage() {
1108 global $wgUser;
1109 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1110 }
1111
1112 /**
1113 * Loads a string into mRestrictions array
1114 * @param string $res restrictions in string format
1115 * @access public
1116 */
1117 function loadRestrictions( $res ) {
1118 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1119 $temp = explode( '=', trim( $restrict ) );
1120 if(count($temp) == 1) {
1121 // old format should be treated as edit/move restriction
1122 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1123 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1124 } else {
1125 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1126 }
1127 }
1128 $this->mRestrictionsLoaded = true;
1129 }
1130
1131 /**
1132 * Accessor/initialisation for mRestrictions
1133 * @param string $action action that permission needs to be checked for
1134 * @return array the array of groups allowed to edit this article
1135 * @access public
1136 */
1137 function getRestrictions($action) {
1138 $id = $this->getArticleID();
1139 if ( 0 == $id ) { return array(); }
1140
1141 if ( ! $this->mRestrictionsLoaded ) {
1142 $dbr =& wfGetDB( DB_SLAVE );
1143 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1144 $this->loadRestrictions( $res );
1145 }
1146 if( isset( $this->mRestrictions[$action] ) ) {
1147 return $this->mRestrictions[$action];
1148 }
1149 return array();
1150 }
1151
1152 /**
1153 * Is there a version of this page in the deletion archive?
1154 * @return int the number of archived revisions
1155 * @access public
1156 */
1157 function isDeleted() {
1158 $fname = 'Title::isDeleted';
1159 if ( $this->getNamespace() < 0 ) {
1160 $n = 0;
1161 } else {
1162 $dbr =& wfGetDB( DB_SLAVE );
1163 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1164 'ar_title' => $this->getDBkey() ), $fname );
1165 }
1166 return (int)$n;
1167 }
1168
1169 /**
1170 * Get the article ID for this Title from the link cache,
1171 * adding it if necessary
1172 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1173 * for update
1174 * @return int the ID
1175 * @access public
1176 */
1177 function getArticleID( $flags = 0 ) {
1178 $linkCache =& LinkCache::singleton();
1179 if ( $flags & GAID_FOR_UPDATE ) {
1180 $oldUpdate = $linkCache->forUpdate( true );
1181 $this->mArticleID = $linkCache->addLinkObj( $this );
1182 $linkCache->forUpdate( $oldUpdate );
1183 } else {
1184 if ( -1 == $this->mArticleID ) {
1185 $this->mArticleID = $linkCache->addLinkObj( $this );
1186 }
1187 }
1188 return $this->mArticleID;
1189 }
1190
1191 function getLatestRevID() {
1192 if ($this->mLatestID !== false)
1193 return $this->mLatestID;
1194
1195 $db =& wfGetDB(DB_SLAVE);
1196 return $this->mLatestID = $db->selectField( 'revision',
1197 "max(rev_id)",
1198 array('rev_page' => $this->getArticleID()),
1199 'Title::getLatestRevID' );
1200 }
1201
1202 /**
1203 * This clears some fields in this object, and clears any associated
1204 * keys in the "bad links" section of the link cache.
1205 *
1206 * - This is called from Article::insertNewArticle() to allow
1207 * loading of the new page_id. It's also called from
1208 * Article::doDeleteArticle()
1209 *
1210 * @param int $newid the new Article ID
1211 * @access public
1212 */
1213 function resetArticleID( $newid ) {
1214 $linkCache =& LinkCache::singleton();
1215 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1216
1217 if ( 0 == $newid ) { $this->mArticleID = -1; }
1218 else { $this->mArticleID = $newid; }
1219 $this->mRestrictionsLoaded = false;
1220 $this->mRestrictions = array();
1221 }
1222
1223 /**
1224 * Updates page_touched for this page; called from LinksUpdate.php
1225 * @return bool true if the update succeded
1226 * @access public
1227 */
1228 function invalidateCache() {
1229 global $wgUseFileCache;
1230
1231 if ( wfReadOnly() ) {
1232 return;
1233 }
1234
1235 $dbw =& wfGetDB( DB_MASTER );
1236 $success = $dbw->update( 'page',
1237 array( /* SET */
1238 'page_touched' => $dbw->timestamp()
1239 ), array( /* WHERE */
1240 'page_namespace' => $this->getNamespace() ,
1241 'page_title' => $this->getDBkey()
1242 ), 'Title::invalidateCache'
1243 );
1244
1245 if ($wgUseFileCache) {
1246 $cache = new CacheManager($this);
1247 @unlink($cache->fileCacheName());
1248 }
1249
1250 return $success;
1251 }
1252
1253 /**
1254 * Prefix some arbitrary text with the namespace or interwiki prefix
1255 * of this object
1256 *
1257 * @param string $name the text
1258 * @return string the prefixed text
1259 * @access private
1260 */
1261 /* private */ function prefix( $name ) {
1262 global $wgContLang;
1263
1264 $p = '';
1265 if ( '' != $this->mInterwiki ) {
1266 $p = $this->mInterwiki . ':';
1267 }
1268 if ( 0 != $this->mNamespace ) {
1269 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1270 }
1271 return $p . $name;
1272 }
1273
1274 /**
1275 * Secure and split - main initialisation function for this object
1276 *
1277 * Assumes that mDbkeyform has been set, and is urldecoded
1278 * and uses underscores, but not otherwise munged. This function
1279 * removes illegal characters, splits off the interwiki and
1280 * namespace prefixes, sets the other forms, and canonicalizes
1281 * everything.
1282 * @return bool true on success
1283 * @access private
1284 */
1285 /* private */ function secureAndSplit() {
1286 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1287 $fname = 'Title::secureAndSplit';
1288 wfProfileIn( $fname );
1289
1290 # Initialisation
1291 static $rxTc = false;
1292 if( !$rxTc ) {
1293 # % is needed as well
1294 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1295 }
1296
1297 $this->mInterwiki = $this->mFragment = '';
1298 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1299
1300 # Clean up whitespace
1301 #
1302 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform );
1303 $t = trim( $t, '_' );
1304
1305 if ( '' == $t ) {
1306 wfProfileOut( $fname );
1307 return false;
1308 }
1309
1310 if( false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1311 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1312 wfProfileOut( $fname );
1313 return false;
1314 }
1315
1316 $this->mDbkeyform = $t;
1317
1318 # Initial colon indicates main namespace rather than specified default
1319 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1320 if ( ':' == $t{0} ) {
1321 $this->mNamespace = NS_MAIN;
1322 $t = substr( $t, 1 ); # remove the colon but continue processing
1323 }
1324
1325 # Namespace or interwiki prefix
1326 $firstPass = true;
1327 do {
1328 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1329 $p = $m[1];
1330 $lowerNs = strtolower( $p );
1331 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1332 # Canonical namespace
1333 $t = $m[2];
1334 $this->mNamespace = $ns;
1335 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1336 # Ordinary namespace
1337 $t = $m[2];
1338 $this->mNamespace = $ns;
1339 } elseif( $this->getInterwikiLink( $p ) ) {
1340 if( !$firstPass ) {
1341 # Can't make a local interwiki link to an interwiki link.
1342 # That's just crazy!
1343 wfProfileOut( $fname );
1344 return false;
1345 }
1346
1347 # Interwiki link
1348 $t = $m[2];
1349 $this->mInterwiki = strtolower( $p );
1350
1351 # Redundant interwiki prefix to the local wiki
1352 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1353 if( $t == '' ) {
1354 # Can't have an empty self-link
1355 wfProfileOut( $fname );
1356 return false;
1357 }
1358 $this->mInterwiki = '';
1359 $firstPass = false;
1360 # Do another namespace split...
1361 continue;
1362 }
1363 }
1364 # If there's no recognized interwiki or namespace,
1365 # then let the colon expression be part of the title.
1366 }
1367 break;
1368 } while( true );
1369 $r = $t;
1370
1371 # We already know that some pages won't be in the database!
1372 #
1373 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1374 $this->mArticleID = 0;
1375 }
1376 $f = strstr( $r, '#' );
1377 if ( false !== $f ) {
1378 $this->mFragment = substr( $f, 1 );
1379 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1380 # remove whitespace again: prevents "Foo_bar_#"
1381 # becoming "Foo_bar_"
1382 $r = preg_replace( '/_*$/', '', $r );
1383 }
1384
1385 # Reject illegal characters.
1386 #
1387 if( preg_match( $rxTc, $r ) ) {
1388 wfProfileOut( $fname );
1389 return false;
1390 }
1391
1392 /**
1393 * Pages with "/./" or "/../" appearing in the URLs will
1394 * often be unreachable due to the way web browsers deal
1395 * with 'relative' URLs. Forbid them explicitly.
1396 */
1397 if ( strpos( $r, '.' ) !== false &&
1398 ( $r === '.' || $r === '..' ||
1399 strpos( $r, './' ) === 0 ||
1400 strpos( $r, '../' ) === 0 ||
1401 strpos( $r, '/./' ) !== false ||
1402 strpos( $r, '/../' ) !== false ) )
1403 {
1404 wfProfileOut( $fname );
1405 return false;
1406 }
1407
1408 # We shouldn't need to query the DB for the size.
1409 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1410 if ( strlen( $r ) > 255 ) {
1411 wfProfileOut( $fname );
1412 return false;
1413 }
1414
1415 /**
1416 * Normally, all wiki links are forced to have
1417 * an initial capital letter so [[foo]] and [[Foo]]
1418 * point to the same place.
1419 *
1420 * Don't force it for interwikis, since the other
1421 * site might be case-sensitive.
1422 */
1423 if( $wgCapitalLinks && $this->mInterwiki == '') {
1424 $t = $wgContLang->ucfirst( $r );
1425 } else {
1426 $t = $r;
1427 }
1428
1429 /**
1430 * Can't make a link to a namespace alone...
1431 * "empty" local links can only be self-links
1432 * with a fragment identifier.
1433 */
1434 if( $t == '' &&
1435 $this->mInterwiki == '' &&
1436 $this->mNamespace != NS_MAIN ) {
1437 wfProfileOut( $fname );
1438 return false;
1439 }
1440
1441 # Fill fields
1442 $this->mDbkeyform = $t;
1443 $this->mUrlform = wfUrlencode( $t );
1444
1445 $this->mTextform = str_replace( '_', ' ', $t );
1446
1447 wfProfileOut( $fname );
1448 return true;
1449 }
1450
1451 /**
1452 * Get a Title object associated with the talk page of this article
1453 * @return Title the object for the talk page
1454 * @access public
1455 */
1456 function getTalkPage() {
1457 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1458 }
1459
1460 /**
1461 * Get a title object associated with the subject page of this
1462 * talk page
1463 *
1464 * @return Title the object for the subject page
1465 * @access public
1466 */
1467 function getSubjectPage() {
1468 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1469 }
1470
1471 /**
1472 * Get an array of Title objects linking to this Title
1473 * Also stores the IDs in the link cache.
1474 *
1475 * @param string $options may be FOR UPDATE
1476 * @return array the Title objects linking here
1477 * @access public
1478 */
1479 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1480 $linkCache =& LinkCache::singleton();
1481 $id = $this->getArticleID();
1482
1483 if ( $options ) {
1484 $db =& wfGetDB( DB_MASTER );
1485 } else {
1486 $db =& wfGetDB( DB_SLAVE );
1487 }
1488
1489 $res = $db->select( array( 'page', $table ),
1490 array( 'page_namespace', 'page_title', 'page_id' ),
1491 array(
1492 "{$prefix}_from=page_id",
1493 "{$prefix}_namespace" => $this->getNamespace(),
1494 "{$prefix}_title" => $this->getDbKey() ),
1495 'Title::getLinksTo',
1496 $options );
1497
1498 $retVal = array();
1499 if ( $db->numRows( $res ) ) {
1500 while ( $row = $db->fetchObject( $res ) ) {
1501 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1502 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1503 $retVal[] = $titleObj;
1504 }
1505 }
1506 }
1507 $db->freeResult( $res );
1508 return $retVal;
1509 }
1510
1511 /**
1512 * Get an array of Title objects using this Title as a template
1513 * Also stores the IDs in the link cache.
1514 *
1515 * @param string $options may be FOR UPDATE
1516 * @return array the Title objects linking here
1517 * @access public
1518 */
1519 function getTemplateLinksTo( $options = '' ) {
1520 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1521 }
1522
1523 /**
1524 * Get an array of Title objects referring to non-existent articles linked from this page
1525 *
1526 * @param string $options may be FOR UPDATE
1527 * @return array the Title objects
1528 * @access public
1529 */
1530 function getBrokenLinksFrom( $options = '' ) {
1531 if ( $options ) {
1532 $db =& wfGetDB( DB_MASTER );
1533 } else {
1534 $db =& wfGetDB( DB_SLAVE );
1535 }
1536
1537 $res = $db->safeQuery(
1538 "SELECT pl_namespace, pl_title
1539 FROM !
1540 LEFT JOIN !
1541 ON pl_namespace=page_namespace
1542 AND pl_title=page_title
1543 WHERE pl_from=?
1544 AND page_namespace IS NULL
1545 !",
1546 $db->tableName( 'pagelinks' ),
1547 $db->tableName( 'page' ),
1548 $this->getArticleId(),
1549 $options );
1550
1551 $retVal = array();
1552 if ( $db->numRows( $res ) ) {
1553 while ( $row = $db->fetchObject( $res ) ) {
1554 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
1555 }
1556 }
1557 $db->freeResult( $res );
1558 return $retVal;
1559 }
1560
1561
1562 /**
1563 * Get a list of URLs to purge from the Squid cache when this
1564 * page changes
1565 *
1566 * @return array the URLs
1567 * @access public
1568 */
1569 function getSquidURLs() {
1570 return array(
1571 $this->getInternalURL(),
1572 $this->getInternalURL( 'action=history' )
1573 );
1574 }
1575
1576 /**
1577 * Move this page without authentication
1578 * @param Title &$nt the new page Title
1579 * @access public
1580 */
1581 function moveNoAuth( &$nt ) {
1582 return $this->moveTo( $nt, false );
1583 }
1584
1585 /**
1586 * Check whether a given move operation would be valid.
1587 * Returns true if ok, or a message key string for an error message
1588 * if invalid. (Scarrrrry ugly interface this.)
1589 * @param Title &$nt the new title
1590 * @param bool $auth indicates whether $wgUser's permissions
1591 * should be checked
1592 * @return mixed true on success, message name on failure
1593 * @access public
1594 */
1595 function isValidMoveOperation( &$nt, $auth = true ) {
1596 global $wgUser;
1597 if( !$this or !$nt ) {
1598 return 'badtitletext';
1599 }
1600 if( $this->equals( $nt ) ) {
1601 return 'selfmove';
1602 }
1603 if( !$this->isMovable() || !$nt->isMovable() ) {
1604 return 'immobile_namespace';
1605 }
1606
1607 $oldid = $this->getArticleID();
1608 $newid = $nt->getArticleID();
1609
1610 if ( strlen( $nt->getDBkey() ) < 1 ) {
1611 return 'articleexists';
1612 }
1613 if ( ( '' == $this->getDBkey() ) ||
1614 ( !$oldid ) ||
1615 ( '' == $nt->getDBkey() ) ) {
1616 return 'badarticleerror';
1617 }
1618
1619 if ( $auth && (
1620 !$this->userCanEdit() || !$nt->userCanEdit() ||
1621 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1622 return 'protectedpage';
1623 }
1624
1625 # The move is allowed only if (1) the target doesn't exist, or
1626 # (2) the target is a redirect to the source, and has no history
1627 # (so we can undo bad moves right after they're done).
1628
1629 if ( 0 != $newid ) { # Target exists; check for validity
1630 if ( ! $this->isValidMoveTarget( $nt ) ) {
1631 return 'articleexists';
1632 }
1633 }
1634 return true;
1635 }
1636
1637 /**
1638 * Move a title to a new location
1639 * @param Title &$nt the new title
1640 * @param bool $auth indicates whether $wgUser's permissions
1641 * should be checked
1642 * @return mixed true on success, message name on failure
1643 * @access public
1644 */
1645 function moveTo( &$nt, $auth = true, $reason = '' ) {
1646 $err = $this->isValidMoveOperation( $nt, $auth );
1647 if( is_string( $err ) ) {
1648 return $err;
1649 }
1650
1651 $pageid = $this->getArticleID();
1652 if( $nt->exists() ) {
1653 $this->moveOverExistingRedirect( $nt, $reason );
1654 $pageCountChange = 0;
1655 } else { # Target didn't exist, do normal move.
1656 $this->moveToNewTitle( $nt, $reason );
1657 $pageCountChange = 1;
1658 }
1659 $redirid = $this->getArticleID();
1660
1661 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1662 $dbw =& wfGetDB( DB_MASTER );
1663 $categorylinks = $dbw->tableName( 'categorylinks' );
1664 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1665 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1666 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1667 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1668
1669 # Update watchlists
1670
1671 $oldnamespace = $this->getNamespace() & ~1;
1672 $newnamespace = $nt->getNamespace() & ~1;
1673 $oldtitle = $this->getDBkey();
1674 $newtitle = $nt->getDBkey();
1675
1676 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1677 WatchedItem::duplicateEntries( $this, $nt );
1678 }
1679
1680 # Update search engine
1681 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1682 $u->doUpdate();
1683 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1684 $u->doUpdate();
1685
1686 # Update site_stats
1687 if ( $this->getNamespace() == NS_MAIN and $nt->getNamespace() != NS_MAIN ) {
1688 # Moved out of main namespace
1689 # not viewed, edited, removing
1690 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1691 } elseif ( $this->getNamespace() != NS_MAIN and $nt->getNamespace() == NS_MAIN ) {
1692 # Moved into main namespace
1693 # not viewed, edited, adding
1694 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
1695 } elseif ( $pageCountChange ) {
1696 # Added redirect
1697 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1698 } else{
1699 $u = false;
1700 }
1701 if ( $u ) {
1702 $u->doUpdate();
1703 }
1704
1705 global $wgUser;
1706 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1707 return true;
1708 }
1709
1710 /**
1711 * Move page to a title which is at present a redirect to the
1712 * source page
1713 *
1714 * @param Title &$nt the page to move to, which should currently
1715 * be a redirect
1716 * @access private
1717 */
1718 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1719 global $wgUser, $wgUseSquid, $wgMwRedir;
1720 $fname = 'Title::moveOverExistingRedirect';
1721 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1722
1723 if ( $reason ) {
1724 $comment .= ": $reason";
1725 }
1726
1727 $now = wfTimestampNow();
1728 $rand = wfRandom();
1729 $newid = $nt->getArticleID();
1730 $oldid = $this->getArticleID();
1731 $dbw =& wfGetDB( DB_MASTER );
1732 $linkCache =& LinkCache::singleton();
1733
1734 # Delete the old redirect. We don't save it to history since
1735 # by definition if we've got here it's rather uninteresting.
1736 # We have to remove it so that the next step doesn't trigger
1737 # a conflict on the unique namespace+title index...
1738 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1739
1740 # Save a null revision in the page's history notifying of the move
1741 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
1742 $nullRevId = $nullRevision->insertOn( $dbw );
1743
1744 # Change the name of the target page:
1745 $dbw->update( 'page',
1746 /* SET */ array(
1747 'page_touched' => $dbw->timestamp($now),
1748 'page_namespace' => $nt->getNamespace(),
1749 'page_title' => $nt->getDBkey(),
1750 'page_latest' => $nullRevId,
1751 ),
1752 /* WHERE */ array( 'page_id' => $oldid ),
1753 $fname
1754 );
1755 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1756
1757 # Recreate the redirect, this time in the other direction.
1758 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1759 $redirectArticle = new Article( $this );
1760 $newid = $redirectArticle->insertOn( $dbw );
1761 $redirectRevision = new Revision( array(
1762 'page' => $newid,
1763 'comment' => $comment,
1764 'text' => $redirectText ) );
1765 $revid = $redirectRevision->insertOn( $dbw );
1766 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1767 $linkCache->clearLink( $this->getPrefixedDBkey() );
1768
1769 # Log the move
1770 $log = new LogPage( 'move' );
1771 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1772
1773 # Now, we record the link from the redirect to the new title.
1774 # It should have no other outgoing links...
1775 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1776 $dbw->insert( 'pagelinks',
1777 array(
1778 'pl_from' => $newid,
1779 'pl_namespace' => $nt->getNamespace(),
1780 'pl_title' => $nt->getDbKey() ),
1781 $fname );
1782
1783 # Purge squid
1784 if ( $wgUseSquid ) {
1785 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1786 $u = new SquidUpdate( $urls );
1787 $u->doUpdate();
1788 }
1789 }
1790
1791 /**
1792 * Move page to non-existing title.
1793 * @param Title &$nt the new Title
1794 * @access private
1795 */
1796 function moveToNewTitle( &$nt, $reason = '' ) {
1797 global $wgUser, $wgUseSquid;
1798 global $wgMwRedir;
1799 $fname = 'MovePageForm::moveToNewTitle';
1800 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1801 if ( $reason ) {
1802 $comment .= ": $reason";
1803 }
1804
1805 $newid = $nt->getArticleID();
1806 $oldid = $this->getArticleID();
1807 $dbw =& wfGetDB( DB_MASTER );
1808 $now = $dbw->timestamp();
1809 $rand = wfRandom();
1810 $linkCache =& LinkCache::singleton();
1811
1812 # Save a null revision in the page's history notifying of the move
1813 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
1814 $nullRevId = $nullRevision->insertOn( $dbw );
1815
1816 # Rename cur entry
1817 $dbw->update( 'page',
1818 /* SET */ array(
1819 'page_touched' => $now,
1820 'page_namespace' => $nt->getNamespace(),
1821 'page_title' => $nt->getDBkey(),
1822 'page_latest' => $nullRevId,
1823 ),
1824 /* WHERE */ array( 'page_id' => $oldid ),
1825 $fname
1826 );
1827
1828 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1829
1830 # Insert redirect
1831 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1832 $redirectArticle = new Article( $this );
1833 $newid = $redirectArticle->insertOn( $dbw );
1834 $redirectRevision = new Revision( array(
1835 'page' => $newid,
1836 'comment' => $comment,
1837 'text' => $redirectText ) );
1838 $revid = $redirectRevision->insertOn( $dbw );
1839 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1840 $linkCache->clearLink( $this->getPrefixedDBkey() );
1841
1842 # Log the move
1843 $log = new LogPage( 'move' );
1844 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1845
1846 # Purge caches as per article creation
1847 Article::onArticleCreate( $nt );
1848
1849 # Record the just-created redirect's linking to the page
1850 $dbw->insert( 'pagelinks',
1851 array(
1852 'pl_from' => $newid,
1853 'pl_namespace' => $nt->getNamespace(),
1854 'pl_title' => $nt->getDBkey() ),
1855 $fname );
1856
1857 # Non-existent target may have had broken links to it; these must
1858 # now be touched to update link coloring.
1859 $nt->touchLinks();
1860
1861 # Purge old title from squid
1862 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1863 $titles = $nt->getLinksTo();
1864 if ( $wgUseSquid ) {
1865 $urls = $this->getSquidURLs();
1866 foreach ( $titles as $linkTitle ) {
1867 $urls[] = $linkTitle->getInternalURL();
1868 }
1869 $u = new SquidUpdate( $urls );
1870 $u->doUpdate();
1871 }
1872 }
1873
1874 /**
1875 * Checks if $this can be moved to a given Title
1876 * - Selects for update, so don't call it unless you mean business
1877 *
1878 * @param Title &$nt the new title to check
1879 * @access public
1880 */
1881 function isValidMoveTarget( $nt ) {
1882
1883 $fname = 'Title::isValidMoveTarget';
1884 $dbw =& wfGetDB( DB_MASTER );
1885
1886 # Is it a redirect?
1887 $id = $nt->getArticleID();
1888 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1889 array( 'page_is_redirect','old_text','old_flags' ),
1890 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1891 $fname, 'FOR UPDATE' );
1892
1893 if ( !$obj || 0 == $obj->page_is_redirect ) {
1894 # Not a redirect
1895 return false;
1896 }
1897 $text = Revision::getRevisionText( $obj );
1898
1899 # Does the redirect point to the source?
1900 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1901 $redirTitle = Title::newFromText( $m[1] );
1902 if( !is_object( $redirTitle ) ||
1903 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1904 return false;
1905 }
1906 } else {
1907 # Fail safe
1908 return false;
1909 }
1910
1911 # Does the article have a history?
1912 $row = $dbw->selectRow( array( 'page', 'revision'),
1913 array( 'rev_id' ),
1914 array( 'page_namespace' => $nt->getNamespace(),
1915 'page_title' => $nt->getDBkey(),
1916 'page_id=rev_page AND page_latest != rev_id'
1917 ), $fname, 'FOR UPDATE'
1918 );
1919
1920 # Return true if there was no history
1921 return $row === false;
1922 }
1923
1924 /**
1925 * Create a redirect; fails if the title already exists; does
1926 * not notify RC
1927 *
1928 * @param Title $dest the destination of the redirect
1929 * @param string $comment the comment string describing the move
1930 * @return bool true on success
1931 * @access public
1932 */
1933 function createRedirect( $dest, $comment ) {
1934 global $wgUser;
1935 if ( $this->getArticleID() ) {
1936 return false;
1937 }
1938
1939 $fname = 'Title::createRedirect';
1940 $dbw =& wfGetDB( DB_MASTER );
1941
1942 $article = new Article( $this );
1943 $newid = $article->insertOn( $dbw );
1944 $revision = new Revision( array(
1945 'page' => $newid,
1946 'comment' => $comment,
1947 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1948 ) );
1949 $revisionId = $revision->insertOn( $dbw );
1950 $article->updateRevisionOn( $dbw, $revision, 0 );
1951
1952 # Link table
1953 $dbw->insert( 'pagelinks',
1954 array(
1955 'pl_from' => $newid,
1956 'pl_namespace' => $dest->getNamespace(),
1957 'pl_title' => $dest->getDbKey()
1958 ), $fname
1959 );
1960
1961 Article::onArticleCreate( $this );
1962 return true;
1963 }
1964
1965 /**
1966 * Get categories to which this Title belongs and return an array of
1967 * categories' names.
1968 *
1969 * @return array an array of parents in the form:
1970 * $parent => $currentarticle
1971 * @access public
1972 */
1973 function getParentCategories() {
1974 global $wgContLang,$wgUser;
1975
1976 $titlekey = $this->getArticleId();
1977 $dbr =& wfGetDB( DB_SLAVE );
1978 $categorylinks = $dbr->tableName( 'categorylinks' );
1979
1980 # NEW SQL
1981 $sql = "SELECT * FROM $categorylinks"
1982 ." WHERE cl_from='$titlekey'"
1983 ." AND cl_from <> '0'"
1984 ." ORDER BY cl_sortkey";
1985
1986 $res = $dbr->query ( $sql ) ;
1987
1988 if($dbr->numRows($res) > 0) {
1989 while ( $x = $dbr->fetchObject ( $res ) )
1990 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1991 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1992 $dbr->freeResult ( $res ) ;
1993 } else {
1994 $data = '';
1995 }
1996 return $data;
1997 }
1998
1999 /**
2000 * Get a tree of parent categories
2001 * @param array $children an array with the children in the keys, to check for circular refs
2002 * @return array
2003 * @access public
2004 */
2005 function getParentCategoryTree( $children = array() ) {
2006 $parents = $this->getParentCategories();
2007
2008 if($parents != '') {
2009 foreach($parents as $parent => $current) {
2010 if ( array_key_exists( $parent, $children ) ) {
2011 # Circular reference
2012 $stack[$parent] = array();
2013 } else {
2014 $nt = Title::newFromText($parent);
2015 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2016 }
2017 }
2018 return $stack;
2019 } else {
2020 return array();
2021 }
2022 }
2023
2024
2025 /**
2026 * Get an associative array for selecting this title from
2027 * the "page" table
2028 *
2029 * @return array
2030 * @access public
2031 */
2032 function pageCond() {
2033 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2034 }
2035
2036 /**
2037 * Get the revision ID of the previous revision
2038 *
2039 * @param integer $revision Revision ID. Get the revision that was before this one.
2040 * @return interger $oldrevision|false
2041 */
2042 function getPreviousRevisionID( $revision ) {
2043 $dbr =& wfGetDB( DB_SLAVE );
2044 return $dbr->selectField( 'revision', 'rev_id',
2045 'rev_page=' . intval( $this->getArticleId() ) .
2046 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2047 }
2048
2049 /**
2050 * Get the revision ID of the next revision
2051 *
2052 * @param integer $revision Revision ID. Get the revision that was after this one.
2053 * @return interger $oldrevision|false
2054 */
2055 function getNextRevisionID( $revision ) {
2056 $dbr =& wfGetDB( DB_SLAVE );
2057 return $dbr->selectField( 'revision', 'rev_id',
2058 'rev_page=' . intval( $this->getArticleId() ) .
2059 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2060 }
2061
2062 /**
2063 * Compare with another title.
2064 *
2065 * @param Title $title
2066 * @return bool
2067 */
2068 function equals( $title ) {
2069 return $this->getInterwiki() == $title->getInterwiki()
2070 && $this->getNamespace() == $title->getNamespace()
2071 && $this->getDbkey() == $title->getDbkey();
2072 }
2073
2074 /**
2075 * Check if page exists
2076 * @return bool
2077 */
2078 function exists() {
2079 return $this->getArticleId() != 0;
2080 }
2081
2082 /**
2083 * Should a link should be displayed as a known link, just based on its title?
2084 *
2085 * Currently, a self-link with a fragment and special pages are in
2086 * this category. Special pages never exist in the database.
2087 */
2088 function isAlwaysKnown() {
2089 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2090 || NS_SPECIAL == $this->mNamespace;
2091 }
2092
2093 /**
2094 * Update page_touched timestamps on pages linking to this title.
2095 * In principal, this could be backgrounded and could also do squid
2096 * purging.
2097 */
2098 function touchLinks() {
2099 $fname = 'Title::touchLinks';
2100
2101 $dbw =& wfGetDB( DB_MASTER );
2102
2103 $res = $dbw->select( 'pagelinks',
2104 array( 'pl_from' ),
2105 array(
2106 'pl_namespace' => $this->getNamespace(),
2107 'pl_title' => $this->getDbKey() ),
2108 $fname );
2109
2110 $toucharr = array();
2111 while( $row = $dbw->fetchObject( $res ) ) {
2112 $toucharr[] = $row->pl_from;
2113 }
2114 $dbw->freeResult( $res );
2115
2116 if( $this->getNamespace() == NS_CATEGORY ) {
2117 // Categories show up in a separate set of links as well
2118 $res = $dbw->select( 'categorylinks',
2119 array( 'cl_from' ),
2120 array( 'cl_to' => $this->getDbKey() ),
2121 $fname );
2122 while( $row = $dbw->fetchObject( $res ) ) {
2123 $toucharr[] = $row->cl_from;
2124 }
2125 $dbw->freeResult( $res );
2126 }
2127
2128 if (!count($toucharr))
2129 return;
2130 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2131 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2132 }
2133
2134 function trackbackURL() {
2135 global $wgTitle, $wgScriptPath, $wgServer;
2136
2137 return "$wgServer$wgScriptPath/trackback.php?article="
2138 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2139 }
2140
2141 function trackbackRDF() {
2142 $url = htmlspecialchars($this->getFullURL());
2143 $title = htmlspecialchars($this->getText());
2144 $tburl = $this->trackbackURL();
2145
2146 return "
2147 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2148 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2149 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2150 <rdf:Description
2151 rdf:about=\"$url\"
2152 dc:identifier=\"$url\"
2153 dc:title=\"$title\"
2154 trackback:ping=\"$tburl\" />
2155 </rdf:RDF>";
2156 }
2157 }
2158 ?>